package com.miniapp.handler;

import com.alibaba.fastjson.JSON;
import com.miniapp.entity.MiniUserProductEntity;
import com.miniapp.service.MiniUserProductService;
import com.miniapp.utils.BaseUtils;
import com.miniapp.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * Created with IntelliJ IDEA.
 * User: linyuchi
 * Date: 2018/6/14
 * Time: 22:09
 * Description: API拦截器 判断app是否已经过期，如果过期，则直接返回异常信息
 */
public class ApiInterceptor implements HandlerInterceptor{
    @Autowired
    private MiniUserProductService miniUserProductService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        String appid = httpServletRequest.getHeader("appid");

        if (BaseUtils.isEmpty(appid)){
            httpServletResponse.setHeader("Content-type", "text/html;charset=UTF-8");
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.getWriter().write(JSON.toJSONString(R.error("非法请求")));
            return false;
        }
//      判断是否已经过期
        MiniUserProductEntity miniUserProduct = miniUserProductService.findByAppid(appid);

        if (miniUserProduct.getRemindDay() == 0){
            httpServletResponse.setHeader("Content-type", "text/html;charset=UTF-8");
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.getWriter().write(JSON.toJSONString(R.error("小程序已经过期")));
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        Enumeration<String> requestEnum =  httpServletRequest.getParameterNames();
        while(requestEnum.hasMoreElements()){
            String key = requestEnum.nextElement();
            String value = httpServletRequest.getParameter(key);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
